<template>
  <view class="login-box">
    <view class="login-bg">
      <view class="login-text">
        <view>您好，</view>
        <view>欢迎使用「煤市通」</view>
      </view>
      <image :src="mylogo" mode="widthFix"></image>
    </view>
    <view class="login-input">
      <view class="input">
        <image class="pre-icon" :src="accountIcon" mode="widthFix"></image>
        <input v-model="loginForm.username" type="text" placeholder="请输入账号" maxlength="30"
          placeholder-class="placeholder" />
      </view>
      <view class="input password">
        <image class="pre-icon" :src="passwordIcon" mode="widthFix"></image>
        <input v-if="isOpenEye" v-model="loginForm.password" type="text" placeholder="请输入密码" maxlength="20"
          placeholder-class="placeholder" />
        <input v-if="!isOpenEye" v-model="loginForm.password" type="password" placeholder="请输入密码" maxlength="20"
          placeholder-class="placeholder" />
        <image class="next-icon" :src="isOpenEye? eyeOpenIcon : eyeCloseIcon" mode="widthFix"
          @click="isOpenEye=!isOpenEye">
        </image>
      </view>
      <view class="button">
        <button @click="handleLogin">
          登 录
        </button>
      </view>
    </view>
    <view class="read">
      <image :src="checkedFlag ? checkImg : uncheckImg" style="width: 30rpx; height: 30rpx" @click="handleChange">
      </image>
      <view>我已阅读并同意</view>
      <view class="agree-box" @click="handlePrivacy">《隐私及用户协议》</view>
    </view>
    <agreement v-if="privacyShow" ref="privacyBox" @handleAgree="handleAgreeFun"></agreement>
  </view>
</template>

<script>
  import config from '@/config';
  import func from '@/utils/funlogin.js';
  import { getTernantIdByOpenId } from '@/api/me.js';
  import { setTenantId } from '@/utils/auth.js';
  import { getOpenIdByCode, insertBatch } from '@/api/login.js';
  import { toast } from '@/utils/common';
  export default {
    name: 'Login',
    data() {
      return {
        checkedFlag: false,
        isOpenEye: false,
        privacyShow: true,
        globalConfig: getApp().globalData.config,
        loginForm: {
          username: '',
          password: '',
          openId: ''
        }
      };
    },
    computed: {
      mylogo() {
        return config.baseImgUrl + '/mst-login-bg.png';
      },
      accountIcon() {
        return config.baseImgUrl + '/mst-account.png';
      },
      passwordIcon() {
        return config.baseImgUrl + '/mst-password.png';
      },
      eyeOpenIcon() {
        return config.baseImgUrl + '/eye-open.png';
      },
      eyeCloseIcon() {
        return config.baseImgUrl + '/eye-close.png';
      },
      checkImg() {
        return config.baseImgUrl + '/checked.png';
      },
      uncheckImg() {
        return config.baseImgUrl + '/unchecked.png';
      }
    },
    onShow() {
      this.getOpenId()
    },
    methods: {
      async getOpenId() {
        const code = await func.wxLogin();
        const { data } = await getOpenIdByCode(code);
        this.loginForm.openId = data
      },
      // 隐私协议
      handlePrivacy() {
        wx.openPrivacyContract();
      },
      handleChange() {
        this.checkedFlag = !this.checkedFlag;
        if (this.checkedFlag) {
          this.$refs.privacyBox.agreeClick(this.checkedFlag);
        }
      },
      //微信授权登录
      handlewsLogin() {
        //登录逻辑梳理
        func.wechatAppLogin();
      },
      // 登录方法
      handleLogin(params) {
        //校验输入
        if (this.loginForm.username === '') {
          this.$modal.msgError('请输入您的账号');
          return;
        }
        if (this.loginForm.password === '') {
          this.$modal.msgError('请输入您的密码');
          return;
        }
        if (!this.checkedFlag) {
          this.$modal.msgError('请勾选用户协议');
          return;
        }
        // 直接登录
        this.pwdLogin();
      },
      // 密码登录
      async pwdLogin() {
        this.$modal.loading('登录中，请耐心等待...');
        // 执行登录
        const res = await getTernantIdByOpenId(this.loginForm.openId);
        if (res.code == 0) {
          setTenantId(res.data);
          this.$store.dispatch('Login', this.loginForm).then((res) => {
            this.$modal.closeLoading();
            if (res.code == 0) {
              // const subMsgIds = config.subMsgIds
              // Object.keys(subMsgIds).forEach(key => {
              //   this.subscriptionMessage(subMsgIds[key])
              // })
              this.$tab.reLaunch('/pages/index');
            } else {
              toast(res.msg);
            }
          });
        } else {
          //用户不存在
          toast(res.msg);
        }
      },
      subscriptionMessage(ids) {
        wx.getSetting({
          withSubscriptions: true,
          success: (res) => {
            // 调起授权界面弹窗
            const switchStatus = res?.subscriptionsSetting?.mainSwitch
            if (switchStatus) {  // 用户打开了订阅消息总开关
              // 用户同意总是保持是否推送消息的选择, 这里表示以后不会再拉起推送消息的授权
              const itemSettings = res.subscriptionsSetting.itemSettings
              if (!itemSettings) {
                this.showModalSubscribeMessage(ids)
                return
              }
              this.openRequestSubscribeMessage(ids)
            } else {
              uni.showToast({
                title: '订阅消息未开启',
                icon: 'error',
                duration: 2000
              })
            }
          },
        })
      },
      showModalSubscribeMessage(ids) {
        wx.showModal({
          title: '提示',
          content: '请授权开通服务通知',
          showCancel: true,
          success: (res) => {
            if (res.confirm) {
              this.openRequestSubscribeMessage(ids)
            }
          }
        })
      },
      openRequestSubscribeMessage(ids) {
        // 调起消息订阅界面
        wx.requestSubscribeMessage({
          tmplIds: ids,
          success: (obj) => {
            insertBatch({
              openId: this.loginForm.openId,
              userName: this.loginForm.username,
              systemTemplateVOS: this.getSuParams(obj, ids)
            })
          }
        })
      },
      getSuParams(data, ids) {
        const keys = Object.keys(data)
        const idList = ids.filter(id => keys.includes(id))
        return idList.map(id => {
          return {
            templateId: id,
            pushType: data[id]
          }
        })
      },
      // 登录成功后，处理函数
      // loginSuccess() {
      //   // 读取菜单权限数据
      //   this.$store.dispatch('GetUserAuthority').then((res) => {
      //     if (res.code == 0) {
      //       this.loginSuccessFul();
      //     }
      //   });
      // },
      // loginSuccessFul() {
      //   // 设置用户信息
      //   this.$store.dispatch('GetInfo').then(() => {
      //     this.$tab.reLaunch('/pages/index');
      //   });
      //   this.$store.dispatch('GetUserDictData');
      //   //获取用户openid
      //   func.AppLoginGetOpenId();
      // },
      handleAgreeFun(data) {
        this.checkedFlag = data == 1 ? true : false
      },
    }
  };
</script>

<style lang="scss">
  .login-box {
    width: 100%;
    height: 100vh;
    background-color: #fff;

    .login-bg {
      position: relative;
      display: flex;
      justify-content: flex-end;

      .login-text {
        position: absolute;
        top: 70px;
        left: 30px;
        font-size: 28px;
        font-weight: bold;
        z-index: 9;
      }
    }

    .login-input {
      padding: 0 30px;

      .input {
        position: relative;

        image.pre-icon {
          position: absolute;
          top: 10px;
          left: 6px;
          width: 24px;
          height: 28px;
        }
      }

      .password {
        input {
          padding-right: 32px;
        }

        image.next-icon {
          position: absolute;
          top: 11px;
          right: 10px;
          width: 20px;
          height: 20px;
        }
      }

      .input+.input {
        margin-top: 10px;
      }

      .input+.button {
        margin-top: 24px;
      }

      input {
        height: 44px;
        border-radius: 4px;
        padding-left: 32px;
        border: 1px solid #c7cede;
      }

      button {
        height: 44px;
        color: #fff;
        border-radius: 4px;
        background: #409efe;
      }
    }
  }

  .placeholder {
    color: #C7CEDE;
  }

  .read {
    position: fixed;
    bottom: 40px;
    font-size: 14px;
    display: flex;
    width: 100%;
    justify-content: center;
    align-items: center;

    >image+view {
      margin-left: 10px;
    }

    .agree-box {
      color: #409eff;
    }
  }
</style>